package fr.cdj.thebox.server;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.cdj.thebox.server.generated.GeneratedConf;

public class ZipServlet extends HttpServlet {
	private static final long serialVersionUID = -8460676379494320200L;
	private static final int DEFAULT_BUFFER_SIZE = 1024 * 100;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");

		String paths = req.getParameter("paths");
		if (paths == null) {
			resp.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		if(paths.isEmpty()) {
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		String[] pathsList = paths.split(";");

		resp.setHeader("Content-Transfer-Encoding", "binary");
		resp.setContentType("application/force-download");
		resp.setBufferSize(DEFAULT_BUFFER_SIZE);

		GeneratedConf gConf = XmlLoader.generateConfFromXmlFile();
		FileManager fm = new FileManager(gConf);
		
		SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy_hh-mm");
		resp.setHeader("Content-Disposition", "attachment; filename=\"download_" + format.format(new Date()) + ".zip\"");
		fm.zipFilesIntoStream(resp.getOutputStream(), pathsList);
	}

}
